﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Android.Content;
using Android;
using Android.Content.Res;
using Android.Net;
using Android.Widget;
using Android.Net.Http;
using Android.OS;
using Android.OS.Storage;
using Environment = Android.OS.Environment;
using Java.IO;
using File = Java.IO.File;
using Uri = Android.Net.Uri;

namespace VoiceCreator
{
    public class CIFlyServiceInstaller
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="assetsApk">例如:SpeechService.apk </param>
        /// <returns></returns>
        public static bool InstallFromAssets(Context context, string assetsApk)
        {
            AssetManager assetManager = context.Assets;
            File apkFile=null;
            //读取assets目录下的apk文件
            using (Stream stream = assetManager.Open(assetsApk))
            {
                if (stream != null)
                {
                    var appFolder = new File(Environment.ExternalStorageDirectory, VCConsts.AppFolderName);

                    var appCatchFolder = new File(appFolder, VCConsts.AppCatchName);
                    if (!appCatchFolder.Exists())
                    {
                        appCatchFolder.Mkdirs();
                    }

                    apkFile = new File(appCatchFolder, assetsApk);
                    if (apkFile.Exists())
                    {
                        apkFile.Delete();
                    }
                    using (OutputStream output = new FileOutputStream(apkFile))
                    {
                        var buffer = new byte[1024];
                        int rc = 0;
                        while ((rc=stream.Read(buffer,0,buffer.Length))>0)
                        {
                            output.Write(buffer,0,rc);
                        }
                    }
                    
                }
            }

            if (apkFile != null)
            {
                InstallApk(context,apkFile);
            }
            return true;
        }

        static void InstallApk(Context context, File apkfile)
        {
            Uri uri = Uri.FromFile(apkfile);
            Intent i=new Intent(Intent.ActionView);
            i.AddFlags(ActivityFlags.NewTask);
            i.SetDataAndType(uri, "application/vnd.android.package-archive");
            context.StartActivity(i);
        }
    }
}
